<template>
  <div class="app-container">
    <el-form ref="form" :model="listQuery" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item prop="iType" label="产品类型">
            <el-select v-model="listQuery.iType" placeholder="请选择产品类型" clearable>
              <el-option
                v-for="item in optionType"
                :key="item.id"
                :label="item.strValue"
                :value="item.strCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="strOperator" label="产品名称">
            <el-input v-model="listQuery.strProductname" placeholder="请输入产品名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="fetchList">搜索</el-button>
          <el-button type="primary" @click="openadd">添加</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-table :data="listData" style="width: 100%" border>
      <!-- <el-table-column type="selection" label="序号"/> -->
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="strImg" label="产品缩略图" width="180" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 100px; height: 100px" :src="row.strImg" />
        </template>
      </el-table-column>
      <el-table-column prop="strShowimg" label="产品展示图" width="180" align="center">
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.strShowimg"
            :preview-src-list="[row.strShowimg]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="strType" label="产品类型" align="center" />
      <el-table-column prop="strProductname" label="产品名称" align="center" />
      <el-table-column type prop="strLink" label="产品链接" align="center">
        <template slot-scope="{row}">
          <a
            :href="row.strLink"
            target="_barnd"
            style="color: #1890ff;text-decoration: underline;"
          >产品链接</a>
        </template>
      </el-table-column>
      <el-table-column prop="strOrgName" label="所属机构" align="center" />
      <el-table-column prop="strCreatetime" label="创建时间" align="center" />
      <el-table-column prop="effectiveTime" label="截止日期" align="center" />
      <el-table-column prop="strOperatorname" label="创建者" align="center" />
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="{row}">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button size="mini" type="primary" @click="handleModify(row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
          <template v-else>
            <span>无权限</span>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="fetchList"
    />
    <!-- dialog -->

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      top="5vh"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogForm" :model="addForm" :rules="rules" label-width="110px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="产品名称" prop="strProductname">
              <el-input v-model="addForm.strProductname" class="inptw200" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="iType" label="产品类型">
              <el-select v-model="addForm.iType" placeholder="请选择产品类型">
                <el-option
                  v-for="item in optionType"
                  :key="item.id"
                  :label="item.strValue"
                  :value="item.strCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="strLink" label="产品链接">
              <el-input v-model="addForm.strLink" placeholder="请输入产品链接" class="inptw200" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="iOrgsysnum" label="所属机构">
              <el-cascader
                v-model="addForm.iOrgsysnum"
                :options="options"
                :props="{ expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist',checkStrictly: true }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="截止日期" prop="effectiveTime">
              <el-date-picker
                v-model="addForm.effectiveTime"
                :picker-options="expireTimeOption"
                prefix-icon="el-icon-date"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择有效期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="strImg" label="产品缩略图">
              <el-upload
                class="avatar-uploader"
                :action="baseImgRUL"
                name="uploadFile"
                :show-file-list="false"
                :on-success="(response, file)=>handleSuccess(response, file, 'addForm', 'strImg','strImgsize')"
                :before-upload="beforeUpload"
              >
                <img v-if="addForm.strImg" :src="addForm.strImg" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="strShowimg" label="产品展示图">
              <el-upload
                class="avatar-uploader"
                :action="baseImgRUL"
                name="uploadFile"
                :show-file-list="false"
                :on-success="(response, file)=>handleSuccess(response, file, 'addForm', 'strShowimg', '', 'strShowimgsize')"
                :before-upload="beforeUpload"
              >
                <img v-if="addForm.strShowimg" :src="addForm.strShowimg" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="addCancelDialog('dialogForm')">取 消</el-button>
        <el-button
          v-if="dialogTitle === optsTiles.add"
          type="primary"
          @click="dialogAddMatrt('dialogForm')"
        >确 定</el-button>
        <el-button v-else type="primary" @click="digupdate('dialogForm')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrglists,
  getSysType,
  getproductInfo,
  deleteproductInfo,
  addProduct,
  updateProduct
} from '@/api/addTag'
import Pagination from '@/components/Pagination'
import mixins from '@/mixins/uploadImg'
import { validURL } from '@/utils/validate'
import { mapGetters } from 'vuex'

const validateValue = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,15}$/ // 1-15个汉字、字母、数字
  if (value === '') {
    callback(new Error('不能为空！'))
  } else if (!reg.test(value)) {
    callback(new Error('只能输入汉字、字母、数字'))
  } else {
    callback()
  }
}
const validateUrl = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (!validURL(value)) {
    callback(new Error('URL地址格式错误，请重新填写'))
  } else {
    callback()
  }
}
export default {
  name: 'Material',
  components: {
    Pagination
  },
  mixins: [mixins],
  props: {},
  data() {
    return {
      model: '',
      dialogVisible: false,
      dialogupdate: false,
      optsTiles: {
        add: '新增产品',
        edit: '修改产品'
      },
      dialogTitle: '新增产品',
      imageUrl: '',
      strOrgnum: [],
      addStrOrgnum: ['1', '102'],
      listQuery: {
        id: '',
        iType: '',
        strProductname: '',
        strOperatorname: '',
        pageNum: '',
        strType: '',
        strOrgName: ''
      },
      rules: {
        strProductname: [
          { required: true, validator: validateValue, trigger: 'blur' }
        ],
        iType: [
          { required: true, message: '请选择产品类型', trigger: 'change' }
        ],
        strLink: [
          { required: false, validator: validateUrl, trigger: 'change' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        effectiveTime: [
          { required: true, message: '请选择截止日期', trigger: 'change' }
        ],
        strImg: [
          {
            required: true,
            message: '请输入产品缩略图',
            trigger: 'change'
          }
        ]
        // strShowimg: [
        //   {
        //     required: false,
        //     message: '请输入产品展示图',
        //     trigger: 'change'
        //   }
        // ]
      },
      addForm: {
        strProductname: '',
        iType: '',
        strLink: '',
        strOperator: '',
        strImg: '',
        strShowimg: '',
        effectiveTime: '',
        iOrgsysnum: '',
        strImgsize:'',    //产品缩略图大小
        strShowimgsize:'',    //产品展示图大小
      },
      updateForm: {
        id: '',
        strProductname: '',
        iType: '',
        strLink: '',
        strOperator: '',
        strDownload: '',
        strShowimg: '',
        strImg: '',
        effectiveTime: '',
        iOrgsysnum: '',
        strImgsize:'',    //产品缩略图大小
        strShowimgsize:'',    //产品展示图大小
      },
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 8.64e7
        }
      },
      listData: [],
      options: [],
      optionType: [],
      optionTag: [],
      iDevTypes: [],
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper'
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum'])
  },
  created() {
    this.fetchList()
    this.getSelectList()
    getOrglists({ iOrgnum: this.$store.getters.iOrgsysnum }).then(res => {
      if (this.$store.getters.iOrgsysnum === -1) {
        this.options = res && res.data
      } else {
        this.options.push(res && res.data)
      }
    })
  },
  methods: {
    getSelectList() {
      getSysType({ typeInfo: [1] }).then(res => {
        this.optionType = res.data[1]
      })
    },
    fetchList() {
      this.listQuery.pageNum = this.pagenum
      this.listQuery.iOrgsysnum = this.$store.getters.iOrgsysnum
      getproductInfo(this.listQuery).then(res => {
        this.listData = res && res.data
        this.total = !res ? 0 : res.total
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        deleteproductInfo({ iProductnum: row.iProductnum })
          .then(res => {
            this.$notify({
              title: '操作成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.fetchList()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    handleModify(row) {
      this.addForm.id = row.id
      this.addForm.strProductname = row.strProductname
      this.addForm.iType = row.iType.toString()
      this.addForm.iProductnum = row.iProductnum
      this.addForm.strLink = row.strLink
      this.addForm.strOperator = row.strOperator
      this.addForm.strShowimg = row.strShowimg
      this.addForm.strImg = row.strImg
      this.addForm.effectiveTime = row.effectiveTime
      this.addForm.iOrgsysnum = row.iOrgsysnum.toString()
      this.addForm.strImgsize = row.strImgsize  //产品缩略图大小
      this.addForm.strShowimgsize = row.strShowimgsize  //产品展示图大小
      // this.dialogupdate = true
      this.dialogTitle = this.optsTiles.edit
      this.dialogVisible = true
      this.$nextTick(_ => {
        this.$refs['dialogForm'].clearValidate()
      })
    },
    openadd() {
      this.addForm.strProductname = ''
      this.addForm.iType = ''
      this.addForm.strLink = ''
      this.addForm.strImg = ''
      this.addForm.strShowimg = ''
      this.addForm.iOrgsysnum = []
      this.addForm.strOperator = this.$store.getters.name
      this.dialogTitle = this.optsTiles.add
      this.dialogVisible = true
    },
    updateCancelDialog(formName) {
      this.dialogupdate = false
      this.$refs[formName].resetFields()
    },
    digupdate(formName) {
      if (this.addForm.iOrgsysnum instanceof Array) {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1)[0]
      } else {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum
      }
      this.addForm.strOperator = this.$store.getters.name
      this.addForm.strOperator = this.$store.getters.iRolesysnum
      this.$refs[formName].validate(valid => {
        if (valid) {
          updateProduct(this.addForm).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.fetchList()
            this.dialogVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addCancelDialog(formName) {
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },
    dialogAddMatrt(formName) {
      if (this.addForm.iOrgsysnum instanceof Array) {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1)[0]
      } else {
        this.addForm.iOrgsysnum = this.addForm.iOrgsysnum
      }
      this.addForm.strOperator = this.$store.getters.userID
      // console.log('sss', this.$refs[formName])
      this.$refs[formName].validate(valid => {
        if (valid) {
          addProduct(this.addForm).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.fetchList()
            this.dialogVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
